package com.qms.repast.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.orhanobut.logger.Logger;
import com.qms.repast.R;
import com.qms.repast.entity.MessageEvent;
import com.qms.repast.ui.base.BaseActivity;
import com.qms.repast.ui.fragment.CalendarDialog;
import com.qms.repast.ui.fragment.PicSettingDialog;
import com.qms.repast.ui.presenter.UserPresenter;
import com.qms.repast.ui.view.IUserView;
import com.qms.repast.utils.ToastUtils;
import com.qms.repast.weidgets.circleimageview.CircleImageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * @author 泅渡者
 * @date 2018/9/10 0010
 * @describe: 个人信息
 */
public class UserActivity extends BaseActivity<UserPresenter> implements IUserView, EasyPermissions.PermissionCallbacks {
	@BindView(R.id.iv_back)
	ImageView ivBack;
	@BindView(R.id.tv_title)
	TextView tvTitle;
	@BindView(R.id.civ_headPic)
	CircleImageView civHeadPic;
	@BindView(R.id.rl_headPic)
	RelativeLayout rlHeadPic;
	@BindView(R.id.tv_userName)
	TextView tvUserName;
	@BindView(R.id.rl_userName)
	RelativeLayout rlUserName;
	@BindView(R.id.tv_userGender)
	TextView tvUserGender;
	@BindView(R.id.rl_userGender)
	RelativeLayout rlUserGender;
	@BindView(R.id.tv_userBirthday)
	TextView tvUserBirthday;
	@BindView(R.id.rl_userBirthday)
	RelativeLayout rlUserBirthday;
	@BindView(R.id.tv_userPhone)
	TextView tvUserPhone;
	@BindView(R.id.rl_userPhone)
	RelativeLayout rlUserPhone;
	@BindView(R.id.tv_userPassword)
	TextView tvUserPassword;
	@BindView(R.id.rl_userPassword)
	RelativeLayout rlUserPassword;
	@BindView(R.id.tv_wxName)
	TextView tvWxName;
	@BindView(R.id.rl_wxName)
	RelativeLayout rlWxName;
	/**
	 * 授权请求码
	 */
	private static final int REQUEST_CODE = 1001;
	/**
	 * 相册请求码
	 */
	private static final int PHOTO_REQUEST = 1002;
	/**
	 * 相机请求码
	 */
	private static final int CAMERA_REQUEST = 1003;
	/**
	 * 裁剪请求码
	 */
	private static final int CLIP_REQUEST = 1004;
	/**
	 * 权限集合
	 */
	private String[] permissions = {Manifest.permission.CAMERA
			, Manifest.permission.WRITE_EXTERNAL_STORAGE
			, Manifest.permission.READ_EXTERNAL_STORAGE};
	/**
	 * 设置头像弹窗
	 */
	private PicSettingDialog picSettingDialog;
	/**
	 * 日期选择弹窗
	 */
	private CalendarDialog calendarDialog;
	/**
	 * 调用照相机返回图片文件
	 */
	private File tempFile;
	/**
	 * 最后显示的图片文件
	 */
	private String mFile;


	@Override
	protected int initLayout () {
		return R.layout.activity_user;
	}

	@Override
	protected void initPresenter (Intent intent) {
		mPresenter = new UserPresenter(this, this);
	}

	@Override
	protected void initView () {
		tvTitle.setText("个人设置");
		checkPermission();
		EventBus.getDefault().register(this);
	}


	@Override
	protected void initData () {

	}

	@Subscribe
	public void onEventMainThread (MessageEvent messageEvent) {
		switch (messageEvent.getCode()) {
			//打开相册
			case 101:
				picSettingDialog.dismiss();
				mPresenter.toPhotoView();
				break;
			//打开相机
			case 102:
				picSettingDialog.dismiss();
				mPresenter.toCameraView();
				break;
			//关闭弹窗
			case 103:
				picSettingDialog.dismiss();
				break;
			//日历取消
			case 104:
				calendarDialog.dismiss();
				break;
			//日历确定
			case 105:
				calendarDialog.dismiss();
				ToastUtils.showToast((String) messageEvent.getMessage());
				break;
			default:
				break;
		}
	}

	@Override
	protected void onDestroy () {
		super.onDestroy();
		if (EventBus.getDefault().isRegistered(this)) {
			EventBus.getDefault().unregister(this);
		}
	}

	@OnClick({R.id.iv_back, R.id.rl_headPic, R.id.rl_userName, R.id.rl_userGender, R.id.rl_userBirthday, R.id.rl_userPhone, R.id.rl_userPassword, R.id.rl_wxName})
	public void onViewClicked (View view) {
		switch (view.getId()) {
			case R.id.iv_back:
				finish();
				break;
			case R.id.rl_headPic:
				if (EasyPermissions.hasPermissions(this, permissions)) {
					mPresenter.showPicDialog();
				} else {
					EasyPermissions.requestPermissions(this, "拍照必要的权限", REQUEST_CODE, permissions);
				}
				break;
			case R.id.rl_userName:
				startActivity(new Intent(this, UpdateNameActivity.class));
				break;
			case R.id.rl_userGender:
				startActivity(new Intent(this, GenderActivity.class));
				break;
			case R.id.rl_userBirthday:
				mPresenter.showCalender();
				break;
			case R.id.rl_userPhone:
				break;
			case R.id.rl_userPassword:
				break;
			case R.id.rl_wxName:
				break;
			default:
				break;
		}
	}

	/**
	 * 检查权限
	 */
	private void checkPermission () {
		if (EasyPermissions.hasPermissions(this, permissions)) {
			ToastUtils.showToast("已经获取权限");
		} else {
			EasyPermissions.requestPermissions(this, "拍照必要的权限", REQUEST_CODE, permissions);
		}
	}


	@Override
	public void onRequestPermissionsResult (int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
	}

	/**
	 * 请求成功
	 *
	 * @param requestCode 请求码
	 * @param perms       成功授权集合
	 */
	@Override
	public void onPermissionsGranted (int requestCode, @NonNull List<String> perms) {
		if (requestCode == REQUEST_CODE) {
			if (perms.contains(permissions)) {
				ToastUtils.showToast("授权成功");
			}
		}
	}

	/**
	 * 请求失败
	 *
	 * @param requestCode 请求码
	 * @param perms       权限失败集合
	 */
	@Override
	public void onPermissionsDenied (int requestCode, @NonNull List<String> perms) {
		if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
			new AppSettingsDialog.Builder(this).build().show();
		}
	}

	/**
	 * Activity 回调
	 *
	 * @param requestCode
	 * @param resultCode
	 * @param data
	 */
	@Override
	protected void onActivityResult (int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
			//调用相机后返回
			case CAMERA_REQUEST:
				if (resultCode == RESULT_OK) {
					//用相机返回的照片去调用剪裁也需要对Uri进行处理
					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
						Uri contentUri = FileProvider.getUriForFile(this, getPackageName() + ".android7.fileprovider", tempFile);
						clipPhotoZoom(contentUri);
					} else {
						clipPhotoZoom(Uri.fromFile(tempFile));
					}
				}
				break;
			//调用相册后返回
			case PHOTO_REQUEST:
				if (resultCode == RESULT_OK) {
					Uri uri = data.getData();
					clipPhotoZoom(uri);
				}
				break;
			//调用剪裁后返回
			case CLIP_REQUEST:
				if (data != null) {
					Bitmap photo = BitmapFactory.decodeFile(mFile);
					civHeadPic.setImageBitmap(photo);
				} else {
					Logger.e("data为空");
				}
				break;
			default:
				break;
		}

	}

	@Override
	public void showPicDialog () {
		if (picSettingDialog == null) {
			picSettingDialog = new PicSettingDialog();
		}
		if (picSettingDialog.isVisible()) {
			picSettingDialog.dismiss();
		} else {
			picSettingDialog.show(getFragmentManager(), "headPic");
		}
	}

	@Override
	public void showCalender () {
		if (calendarDialog == null) {
			calendarDialog = new CalendarDialog();
		}
		if (calendarDialog.isVisible()) {
			calendarDialog.dismiss();
		} else {
			calendarDialog.show(getFragmentManager(), "calender");
		}
	}

	@Override
	public void toPhotoView () {
		Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
		photoPickerIntent.setType("image/*");
		startActivityForResult(photoPickerIntent, PHOTO_REQUEST);
	}

	@Override
	public void toCameraView () {
		//用于保存调用相机拍照后所生成的文件
		tempFile = new File(Environment.getExternalStorageDirectory().getPath(), System.currentTimeMillis() + ".png");
		//跳转到调用系统相机
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		//如果在Android7.0以上,使用FileProvider获取Uri
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
			intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
			Uri contentUri = FileProvider.getUriForFile(this, getPackageName() + ".android7.fileprovider", tempFile);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
		}
		//否则使用Uri.fromFile(file)方法获取Uri
		else {
			intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
		}
		startActivityForResult(intent, CAMERA_REQUEST);
	}


	private void clipPhotoZoom (Uri uri) {
		if (uri == null) {
			Logger.d("The uri is not exist.");
		}
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
		intent.setDataAndType(uri, "image/*");
		// 设置裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 100);
		intent.putExtra("outputY", 100);
		intent.putExtra("return-data", false);
		File out = new File(getPath());
		if (!out.getParentFile().exists()) {
			out.getParentFile().mkdirs();
		}
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(out));
		startActivityForResult(intent, CLIP_REQUEST);
	}

	/**
	 * 裁剪后地址
	 *
	 * @return
	 */
	public String getPath () {
		if (mFile == null) {
			mFile = Environment.getExternalStorageDirectory() + "/outtemp.png";
		}
		return mFile;
	}

}
